package com.ys.controller.api.overseas;

import com.ys.config.MenuId;
import com.ys.entity.overseas.TosProductSelection;
import com.ys.entity.sys.YsCol;
import com.ys.service.overseas.TosProductSelectionService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-17
 * @Description: HW商品选品库控制层
 * @Version: 1.5
 */
@CrossOrigin
@Controller
@RequestMapping("/api/inter/tosProductSelection")
public class TosProductSelectionController {
    private static final Logger logger = LoggerFactory.getLogger(TosProductSelectionController.class);


    @Autowired
    private TosProductSelectionService tosProductSelectionService;

    @Autowired
    private CommonApiService<TosProductSelection> commonApiService;

    public TosProductSelection setSeachSql(TosProductSelection cond){
        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS createUser")//创建人
        .addLeftJoin("TOS_ProductSelectionItem B ON B.pid = A.id")
        .addField("B.code,B.productImg,B.fromCode,B.productName,B.productTitle,B.productCategory,B.purchaseAmount,B.deliveryAmount,B.suggestAmount,B.profitAmount,B.profitRatio")//子表商品信息
        .addLeftJoin("TOS_PlatformInformation C ON B.platformId = C.id")
        .addField("C.platformCode,C.hwName,C.regionName,C.currencyCode")//平台信息
        .addLeftJoin("YS_ProcInst L ON L.Bid = A.Bid ")
        .addField("FORMAT(L.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间
        .addLeftJoin("TOS_ChannelStock cs ON cs.productCode = B.code")
        .where("cs.stockNum >0")
        ;
        return cond;
    }

    @RequiresPermissions("tosProductSelection:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TosProductSelection cond
    ){

        setSeachSql(cond);
        cond = commonApiService.dataAuth(MenuId.TOS_ProductSelection, cond);
        return commonApiService.searchLay(cond);
    }

    /**
     * 新增
     */
    @RequiresPermissions("tosProductSelection:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params, String subData
    ) {
        try {
            logger.info("HW商品选品库新增传参：" + params);
            //修改
            return tosProductSelectionService.add(params,subData);
        } catch (Exception e) {
            logger.error("HW商品选品库新增出错：", e.getMessage(), e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改
     */
    @RequiresPermissions("tosProductSelection:add")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params, String subData
    ) {
        try {
            logger.info("HW商品选品库修改传参：" + params);
            //修改
            return tosProductSelectionService.edit(params,subData);
        } catch (Exception e) {
            logger.error("HW商品选品库修改出错：", e.getMessage(), e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除
     */
    @RequiresPermissions("tosProductSelection:add")
    @RequestMapping("/deleteTrue")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            return tosProductSelectionService.del(id);
        } catch (Exception e) {
            logger.error("删除HW商品选品库出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    @RequiresPermissions("tosProductSelection:add")
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tosProductSelectionService.flowPass(id, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("HW商品选品库审批出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions("tosProductSelection:add")
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            return tosProductSelectionService.flowRefuse(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("HW商品选品库退回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @RequiresPermissions("tosProductSelection:add")
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            return tosProductSelectionService.flowInit(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("HW商品选品库驳回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TosProductSelection cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            setSeachSql(cond);
            cond = commonApiService.dataAuth(MenuId.TOS_ProductSelection, cond);
            ;
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TOS_ProductSelection)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TosProductSelection> util = new ExportExcelUtils<>(new TosProductSelection());
            String toFilePath = util.exportExcelWithDict(listData, listField, "HW商品选品库报表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * HW商品选品(HW采购计划单调用)
     * @param model
     * @param request
     * @param response
     * @param cond
     * @return
     */
    @RequestMapping("/searchJh")
    @ResponseBody
    public LayuiTableVoJA searchJh(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TosProductSelection cond,String vgsBm
    ){

        setSeachSql(cond);
        cond.addLeftJoin("TOS_ChannelStock tcs ON tcs.ProductCode = B.code");
        cond.where("A.effectStock = 1 AND A.vgsBm = '"+ vgsBm+"'");
        cond.addField("B.id productSelectionItemId");
        cond.addField("tcs.StockNum purchaseNum");
        cond.addField("B.platformId platformId");
        cond = commonApiService.dataAuth(MenuId.TOS_PurchasePlan, cond);
        return commonApiService.searchLay(cond);
    }
}
